import axios, { type Method } from 'axios'
import { useUserStore } from '@/stores'
import router from '@/router'
import { showToast } from 'vant'

import type { MyResponseType } from '@/types/http'

export const baseURL = 'https://consult-api.itheima.net'

const instance = axios.create({
  baseURL,
  timeout: 10000
})

instance.interceptors.request.use(
  (config) => {
    const userStore = useUserStore()
    let userConfigHeaders = {}
    const token = userStore.user?.token
    if (token) {
      userConfigHeaders = { Authorization: `Bearer ${token}` }
    }
    config.headers = Object.assign({}, userConfigHeaders, config.headers)
    return config
  },
  (err) => Promise.reject(err)
)

instance.interceptors.response.use(
  (res) => {
    if (res.data?.code !== 10000) {
      showToast(res.data?.message || '业务失败')
      return Promise.reject(res.data)
    }
    // 业务逻辑成功，返回响应数据，作为axios成功的结果
    return res.data
  },
  (err) => {
    if (err.response?.status === 401) {
      const userStore = useUserStore()
      userStore.clearUser()
      showToast('登录信息失效，请重新登录')
      setTimeout(() => {
        router.push({
          path: '/login',
          params: {
            returnUrl: router.currentRoute.value.fullPath
          }
        })
      }, 1000)
    } else {
      showToast(err.response?.data?.mssage || '请求失败')
    }
    return Promise.reject(err.response?.data || err)
  }
)

const http = <Type = any>(
  url: string,
  method: Method = 'get',
  requestData?: object
) => {
  return instance.request<Type, MyResponseType<Type>>({
    url,
    method,
    [method.toLowerCase() === 'get' ? 'params' : 'data']: requestData
  })
}

http.get = <ResType = any>(url: string, params?: object) => {
  return http<ResType>(url, 'get', params)
}
http.post = <ResType = any>(url: string, data: object) => {
  return http<ResType>(url, 'post', data)
}
http.delete = <ResType = any>(url: string, id: string) => {
  return http<ResType>(`${url}/${id}`, 'delete')
}

http.put = <ResType>(url: string, data?: object) => {
  return instance.request<ResType>({
    url,
    method: 'put',
    data
  })
}

export default http as typeof http
